package com.senjoeson.abilityservice;

import android.app.Instrumentation;
import android.app.UiAutomation;
import android.os.ParcelFileDescriptor;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
public class ShellCommandBuilder {
    private final LinkedList<String> mCommands = new LinkedList<>();
    private final Instrumentation mInstrumentation;
    public static ShellCommandBuilder create(Instrumentation instrumentation) {
        return new ShellCommandBuilder(instrumentation);
    }
    private ShellCommandBuilder(Instrumentation instrumentation) {
        mInstrumentation = instrumentation;
    }
    public void run() {
        final UiAutomation automation = mInstrumentation.getUiAutomation(
                UiAutomation.FLAG_DONT_SUPPRESS_ACCESSIBILITY_SERVICES);
        for (String command : mCommands) {
            execShellCommand(automation, command);
        }
    }
    public ShellCommandBuilder deleteSecureSetting(String name) {
        mCommands.add("settings delete secure " + name);
        return this;
    }
    public ShellCommandBuilder putSecureSetting(String name, String value) {
        mCommands.add("settings put secure " + name + " " + value);
        return this;
    }
    public ShellCommandBuilder grantPermission(String packageName, String permission) {
        mCommands.add("pm grant " + packageName + " " + permission);
        return this;
    }
    public ShellCommandBuilder addCommand(String command) {
        mCommands.add(command);
        return this;
    }
    private static void execShellCommand(UiAutomation automation, String command) {
        try (ParcelFileDescriptor fd = automation.executeShellCommand(command)) {
            try (InputStream inputStream = new FileInputStream(fd.getFileDescriptor())) {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                    while (reader.readLine() != null) {
                        // Keep reading.
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Failed to exec shell command", e);
        }
    }
}